package be.ipl.servlet;

import java.io.IOException;
import java.util.List;


import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.domaine.Partie;
import be.ipl.ucc.GestionJoueur;
import be.ipl.ucc.GestionParties;

/**
 * Servlet implementation class seLoguer
 */
@WebServlet(name = "login.html")
public class SeLoguer extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GestionJoueur joueur;
	@EJB
	private GestionParties gestiondeparties;
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String mdp = request.getParameter("mdp");

		if (login == null || mdp == null || login == "" || mdp == "") {
			request.setAttribute("message",
					"Vous devez introduire un login et mot de passe");
			RequestDispatcher rd = getServletContext().getNamedDispatcher(
					"ErreurParam");
			rd.forward(request, response);
			return;
		}

		
		boolean connexionOK;
		
		try{
			connexionOK = joueur.authentificationJoueur(login, mdp);
			
			if (connexionOK) {
				HttpSession session = request.getSession();
				synchronized (session) {
					if (session.getAttribute("login") == null)
						session.setAttribute("login", login);
				}
				request.setAttribute("login",
						login);
				
				List<Partie> liste = gestiondeparties.listerPartiesARejoindre();
				request.setAttribute("liste",
						liste);
		
				List<Partie> liste2 = gestiondeparties.listerPartiesAReprendre(login);
				request.setAttribute("liste2",
						liste2);
				
				getServletContext().getNamedDispatcher("accueil.html").forward(
						request, response);
			} else {
				request.setAttribute("message",
						"Login ou mot de passe incorrect.");
				RequestDispatcher rd = getServletContext().getNamedDispatcher(
						"ErreurParam");
				rd.forward(request, response);
				return;
			}
			
		}catch(Exception e){
			request.setAttribute("message",
					"Probleme au niveau serveur : " + e.getMessage());
			RequestDispatcher rd = getServletContext().getNamedDispatcher(
					"ErreurParam");
			rd.forward(request, response);
			return;
		}
	}
}
